package com.wdg.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.StringJoiner;

@Slf4j
public class HttpClientUtil {

    private static final RestTemplate restTemplate = new RestTemplate();
    public static String doGet(String url, Map<String,Object> queryParams){
        StringJoiner joiner = new StringJoiner("&");
        for (String key : queryParams.keySet()) {
            joiner.add(key + "=" + queryParams.get(key));
        }
        url = url + "?" + joiner;
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        return response.getBody();
    }

    public static String doPost(String url, Map<String,Object> queryParam) throws JsonProcessingException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);//这里可能根据需要改成application/json方式
        ObjectMapper objectMapper = new ObjectMapper();
        String queryString = objectMapper.writeValueAsString(queryParam);
        HttpEntity<String> entity = new HttpEntity<>(queryString, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        return response.getBody();
    }
}
